﻿using System;
using Microsoft.AspNetCore.Components.Forms;
using VegetableSale.NET.Dao;
using VegetableSale.NET.Entities;

namespace VegetableSale.NET.Services;

public class StockService
{
    private StockMapper stockMapper = new StockMapper();

    private GoodService goodService = new GoodService();

    private GoodMapper goodMapper = new GoodMapper();

    public Result getStockList(QueryDTO queryDTO)
    {
        StockPage stockPage = new StockPage();
        uint pageNo = queryDTO.PageNo;
        uint pageSize = queryDTO.PageSize;
        List<Stock> stocks = stockMapper.getStockList(queryDTO);
        List<Stock> returnStocks = new List<Stock>();

        if (pageSize * pageNo - 1 >= stocks.Count)
        {
            for (uint i = pageSize * (pageNo - 1); i <= stocks.Count - 1; i++)
            {
                Stock stock = stocks[(int) i];
                returnStocks.Add(stock);
            }
        }
        else
        {
            for (uint i = pageSize * (pageNo - 1); i <= pageSize * pageNo - 1; i++)
            {
                Stock stock = stocks[(int) i];
                returnStocks.Add(stock);
            }
        }

        stockPage.Records = returnStocks;
        stockPage.Pages = (int) pageNo;
        stockPage.Size = pageSize;
        stockPage.Total = (uint) stocks.Count;

        return new Result(200, "搜索成功", stockPage);
    }

    public Result addStock(StockQuery stockQuery)
    {
        goodService.updateInventory(stockQuery.Commid, stockQuery.Sknumber, "+");
        stockMapper.addStock(stockQuery);
        return new Result(200, "插入成功", "");
    }

    public Result deleteStock(int skid)
    {
        List<Object> updateDate = stockMapper.getDeleteStock(skid);
        goodService.updateInventory((int) updateDate[0], (int) updateDate[1], "-");
        stockMapper.deleteStock(skid);
        return new Result(200, "删除成功", "");
    }

    public Result updateStock(StockUpdateQuery stockUpdateQuery)
    {
        Stock stock = stockMapper.getStockById(stockUpdateQuery.Skid);
        //double inventory = goodMapper.getInventoryById(stockUpdateQuery.Commid);
        if (stock.Sknumber >= stockUpdateQuery.Sknumber)
        {
            int change = stock.Sknumber - stockUpdateQuery.Sknumber;
            goodService.updateInventory(stockUpdateQuery.Commid, change, "-");
        }
        else
        {
            int change = stockUpdateQuery.Sknumber - stock.Sknumber;
            Console.WriteLine("Change:" + change);
            goodService.updateInventory(stockUpdateQuery.Commid, change, "+");
        }

        stockMapper.updateStock(stockUpdateQuery);
        return new Result(200, "修改成功", "");
    }
}